package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	}
}

func main() {
	engine := gin.Default()
	engine.Use(CORSMiddleware(), Rquest())
	// 全局用法
	engine.GET("test/:a", func(ctx *gin.Context) {
		s, _ := ctx.Params.Get("a")
		ctx.String(http.StatusOK, "success. _%s_", s)
	})
	// 局部用法 - 接口单独增加中间件
	engine.GET("test/any", AnyRquest(), func(ctx *gin.Context) {
		s, _ := ctx.Params.Get("b")
		ctx.String(http.StatusOK, "any success. _%s_\n", s)
	})

	if err := engine.Run(":8080"); err != nil {
		log.Printf("gin start :8080 fail. \n")
	}
}

// 全局
func Rquest() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 前置
		token := ctx.GetHeader("Authorization")
		if token == "" {
			ctx.String(http.StatusBadRequest, "invalid request.\n")
			ctx.Abort() // 终止请求
			return
		}
		ctx.Next() // 执行业务
		// 后置
		fmt.Println(token)
	}
}

// 局部
func AnyRquest() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 前置
		fmt.Println("any request bgn")
		ctx.Next() // 执行业务
		// 后置
		fmt.Println("any request end")
	}
}
